package huayang.ws;

import huayang.ws.util.JacksonUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * Created by buhuayang on 16/7/12.
 */
public class ChatRoomHandler extends TextWebSocketHandler {

    private static final Logger logger = LoggerFactory.getLogger(ChatRoomHandler.class);

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) {
        try {
            _sendToAllSession(session, message, false);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session)
            throws Exception {
        String httpSessionId = (String) session.getAttributes().get(HttpSessionHandshakeInterceptor.HTTP_SESSION_ID_ATTR_NAME);
        ChatRoomSessionData sessionData = WebContent.httpSessionDataMap.get(httpSessionId);
        sessionData.setSocketSession(session);
        WebContent.socketSessionDataMap.put(session.getId(), sessionData);
        logger.info("登录信息[username:{},httpSessionId:{},socketSessionId:{}]成功连接聊天室",
                sessionData.getUsername(), httpSessionId, session.getId());
        MsgInfo msgInfo = new MsgInfo();
        msgInfo.setType("list-changed");
        _sendToAllSession(session, msgInfo, false);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session,
                                      CloseStatus closeStatus) throws Exception {
        ChatRoomSessionData sessionData = WebContent.socketSessionDataMap.get(session.getId());
        logger.info("登出信息[username:{},httpSessionId:{},socketSessionId:{}]成功断开连接聊天室",
                sessionData.getUsername(), sessionData.getHttpSessionId(), session.getId());
        MsgInfo msgInfo = new MsgInfo();
        msgInfo.setType("list-changed");
        _sendToAllSession(session, msgInfo, false);
    }

    private void _sendToAllSession(WebSocketSession session, MsgInfo msgInfo, boolean isIncludeMe) throws IOException {
        Set<String> socketSessionMapKeyset = WebContent.socketSessionDataMap.keySet();
        for (String key : socketSessionMapKeyset) {
            ChatRoomSessionData sessionData = WebContent.socketSessionDataMap.get(key);
            WebSocketSession socketSession = sessionData.getSocketSession();
            if (socketSession.isOpen()) {
                if (!isIncludeMe && StringUtils.equals(session.getId(), sessionData.getSocketSession().getId())) {
                    continue;
                }
                TextMessage textMessage = new TextMessage(JacksonUtil.writeObj2Json(msgInfo).getBytes("UTF-8"));
                socketSession.sendMessage(textMessage);
            }
        }
    }

    private void _sendToAllSession(WebSocketSession session, TextMessage textMessage, boolean isIncludeMe) throws IOException {
        Set<String> socketSessionMapKeyset = WebContent.socketSessionDataMap.keySet();
        for (String key : socketSessionMapKeyset) {
            ChatRoomSessionData sessionData = WebContent.socketSessionDataMap.get(key);
            WebSocketSession socketSession = sessionData.getSocketSession();
            if (socketSession.isOpen()) {
                if (!isIncludeMe && StringUtils.equals(session.getId(), sessionData.getSocketSession().getId())) {
                    continue;
                }
                socketSession.sendMessage(textMessage);
            }
        }
    }

}
